const Api = {
	request: data => {
		return new Promise((resolve, reject) => {
			$.ajax({
				url: "http://music.muoutv.com/api.php",
				data,
				dataType: "jsonp",
				success: res => resolve(res),
				error: (xhr, status, error) => reject(error)
			})
		})
	}
}

$(function() {
	$(".search .input").on("keyup", async function(e) {
		const code = e.which
		if(code == 13) {
			const name = $(this).val(), types = "search"
			try {
				const songs = await Api.request({types, name})
				if(songs.length > 0) {
					$(".list").removeClass("hide")
					$(".list table tbody").empty()
					songs.forEach((song, idx) => {
						const line = `<tr rel='song-item' data-id='${song.id}' data-source='${song.source}' data-name='${song.name}' data-artist='${song.artist.join('; ')}' data-album='${song.album}'><td>${idx + 1}</td><td>${song.name}</td><td>${song.artist.join('; ')}</td><td>${song.album}</td></tr>`
						$(".list table tbody").append(line)
					})
				} else {
					$(".list").addClass("hide")
				}
				// console.log(res)
			} catch(error) {
				console.error(error)
			}
		}
	})

	$(document).on("click", "tr[rel='song-item']", async function(e) {
		// console.log(e)
		const {id, source, name, artist, album} = e.currentTarget.dataset, types = "url"
		const res = await Api.request({id, source, types})
		if(res.url) {
			$(".player .title").html(name + "  歌手：" + artist + "  专辑：" + album)
			$("#jplayer").jPlayer("setMedia", {mp3: res.url})
			$("#jplayer").jPlayer("play")
		}
		// console.log(res)
	})

	$("#jplayer").jPlayer({
		cssSelectorAncestor: "",
		cssSelector: {
			duration: ".player .duration",
			currentTime: ".player .current-time"
		},
		timeupdate: e => {
			const {duration, currentTime} = e.jPlayer.status,
			progress = currentTime / duration * 100
			$(".player .progress .current-progress").css("width", progress + "%")
			$(".player .progress .current-progress-dot").css("left", progress + "%")
			// console.log(res)
		}
	})
})
